% ctex-cjk-engine.def: for LaTeX engine with CJK
% vim:ft=tex

\AtEndPreamble{%
  \@ifpackageloaded{mathstyle}{% preload CJK env
    \CJK{\CTEX@encoding}{}\endCJK}{}}

\ifCTEX@engine{zhmCJK}{
  \RequirePackage[encoding=\CTEX@encoding]{zhmCJK}
  \endinput
}{}

\RequirePackage{xpatch}

\def\CTEX@inputzhmap#1{%
  \def\CJKrmdefault{rm}%
  \def\CJKsfdefault{sf}%
  \def\CJKttdefault{tt}%
  \AtBeginDvi{\input{#1}}%
  \AtBeginDocument{% 兼容 eso-pic 等
    \@ifpackageloaded{atbegshi}
      {\AtBeginShipoutFirst{\input{#1}}}{}
  }
}

\ifCTEX@encoding{GBK}
  {\RequirePackage{CJK}[2003/03/28]}
  {\RequirePackage{CJKutf8}[2003/03/28]}

\ifbool{CTEX@punct}
  {\RequirePackage{CJKpunct}[2009/05/06]}{}

\ifbool{CTEX@CJKspace}
  {\RequirePackage{CJKspace}}{}

\ifbool{CTEX@space}{%
  \def\CTEX@CJKenv{CJK}%
  \let\CTEX@tilde\empty
}{%
  \def\CTEX@CJKenv{CJK*}%
  \def\CTEX@tilde{\CJKtilde}%
}

\def\CTEX@beginCJK{%
  \begin{\CTEX@CJKenv}{\CTEX@encoding}{\CJKfamilydefault}%
  \CTEX@tilde}
\def\CTEX@endCJK{\clearpage\end{\CTEX@CJKenv}}

\AtEndOfPackage{\CJK@makeActive}

\appto\document{\CTEX@beginCJK\ignorespaces}
\preto\enddocument{\CTEX@endCJK}

\def\CJKfamilydefault{\CJKrmdefault}

\providecommand*\CJKrmdefault{gbsn}
\providecommand*\CJKsfdefault{gbsn}
\providecommand*\CJKttdefault{gbsn}

\xpretocmd\rmfamily{\CJKfamily{\CJKrmdefault}}{}{}
\xpretocmd\sffamily{\CJKfamily{\CJKsfdefault}}{}{}
\xpretocmd\ttfamily{\CJKfamily{\CJKttdefault}}{}{}
\xpretocmd\normalfont{\CJKfamily{\CJKfamilydefault}}
  {\let\reset@font\normalfont}{}

\endinput
